package org.jeecg.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class DateTimeUtil {

    public static int betweenMonthByTwoCalendar(Calendar startCalendar, Calendar endCalendar) {
        //判断日期大小
        if (startCalendar.after(endCalendar)) {
            Calendar temp = startCalendar;
            startCalendar = endCalendar;
            endCalendar = temp;
        }
        int startYear = startCalendar.get(Calendar.YEAR);
        int endYear = endCalendar.get(Calendar.YEAR);
        int startMonth = startCalendar.get(Calendar.MONTH);
        int endMonth = endCalendar.get(Calendar.MONTH);
        int monthNum = (endYear - startYear) * 12 + (endMonth - startMonth);
        return monthNum;
    }


    public static List<String> getMonthRange(String beginTime, String endTime) throws ParseException {
        List<String> range = new ArrayList<>();
        String dateFormat = "yyyy-MM";
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        Calendar beginCalendar = DateUtils.parseCalendar(beginTime, dateFormat);
        Calendar endCalendar = DateUtils.parseCalendar(endTime, dateFormat);

        int diff = betweenMonthByTwoCalendar(beginCalendar, endCalendar);
//       System.out.printf("\n\n\n diff %s \n\n\n", JSONObject.toJSONString(diff));
        if (diff > 0) {
            for (int i = 0; i < diff; i++) {
                String nextMonth = sdf.format(beginCalendar.getTime());
                range.add(nextMonth);
                beginCalendar.add(Calendar.MONTH, 1);
            }
        }


        return range;
    }

    public static String[] getLast12Months() {

        String[] last12Months = new String[12];

        Calendar cal = Calendar.getInstance();
        for (int i = 0; i < 12; i++) {


            if (cal.get(Calendar.MONTH) - i < 1) {
                last12Months[11 - i] = cal.get(Calendar.YEAR) - 1 + "-" + fillZero((cal.get(Calendar.MONTH) - i + 12 * 1));
            } else {
                last12Months[11 - i] = cal.get(Calendar.YEAR) + "-" + fillZero((cal.get(Calendar.MONTH) - i));
            }

            System.out.println(last12Months[11 - i]);
        }

        return last12Months;
    }


    public static String fillZero(int i) {
        String str = "";
        if (i > 0 && i < 10) {
            str = "0" + i;
        } else {
            str = "" + i;
        }
        return str;

    }
}
